$package('wstuo.infoMge');
$import("wstuo.user.userUtil");
 /**  
 * @author Wstuo  
 * @constructor IMMessage
 * @description 即时消息主函数. tools/im.jsp
 * @since version 1.0 
 */
wstuo.infoMge.infoMge = function() 
{
	
	var id = '';
	var param;
	var receive='';
	return {
		
		/**
		 * @description 打开新增窗口.
		 */
		add_im_openwindow:function(){
			
			windows('addMessage',{width:500});
		},

		/**
		 * @description 打开搜索窗口.
		 */
		search_openwindow:function(){		
			windows('searchImmanage',{width:400});
		},
		
		/**
		 * @description 执行搜索操作.
		 */
		search_do:function(){
				//获得表单对象
				var sdata = $('#searchImmanage form').getForm();		
				var postData = $("#IMjqGrid").jqGrid("getGridParam", "postData");
				$.extend(postData, sdata);  
				var _url = 'immanage!findPager.action';	
				$('#IMjqGrid').trigger('reloadGrid');
				return false;
		},
		
		/**
		 * @description 检查用户是否存在
		 */
		checkUsers:function(userNames,method){
			
			var url='user!vaildateUserByFullName.action';
			var _param = $.param({'userNames':userNames},true);
		
			$.post(url,_param, function(res){
				if(res==true || res=="true"){					
					method();
				}else{
					msgAlert(i18n['msg_msg_userNotExist'],'info');
				}
			});
		
		},

		
		/**
		 * @description 取得接收用户参数
		 */
		getReceiveUsers:function(userNames){
			
			
			var receivesUsers='';
			
			for(var i=0;i<userNames.length;i++){
				
				if(userNames[i]!=userName && userNames[i]!=''){
					
					if(receivesUsers==''){
						
						receivesUsers='receiveUsers='+userNames[i];
					}else{
						receivesUsers+="&receiveUsers="+userNames[i];
					}	
				}
			}
			return receivesUsers;
		},

		/**
		 * @description 发送临时消息.
		 */
		add_instanceMessage:function(){	
			var title= $('#title').val();
			$('#title').val(trim(title));
			var add_content= $('#add_content').val();
			$('#add_content').val(trim(add_content));
				startLoading();
				wstuo.infoMge.infoMge.im_excutionCurrentUser('#receiveUsers');
				validateUsers($('#receiveUsers').val(),function(userNames){
						var _param = $('#addMessage form').serialize();
						var _url='immanage!save.action';

						var receivesUsers=wstuo.infoMge.infoMge.getReceiveUsers(userNames);
						
						$.post(_url,_param+"&"+receivesUsers,function(){	
							
							$('#addMessage').dialog('close');
							$('#IMjqGrid').trigger('reloadGrid');
							
							$('#receiveUsers').val('');
							$('#title').val('');
							$('#add_content').val('');
							endLoading();
							msgShow(i18n['msg_im_imSendSuccessful'],'show');
						});
				});
		
		},
		/**
		 * @description  回复
		 */
		im_reply_imgridact:function(gr){
			$('#rep_content').val('');
			receive='';
			$('#rep_toUser').val('');
			var receiveUsers='';
			if(gr!=null && gr!=''){
				param = $.param({'ids':gr},true);
				if(gr==null & gr==''){
					msgAlert(i18n['msg_atLeastChooseOneData'],'info');
				}else{
					gr=gr+'';
					var mygr=gr.split(",");
					for(var i=0;i<mygr.length;i++){
						var rowData=$("#IMjqGrid").getRowData(mygr[i]);	
						if(rowData.status=='0'){//如果状态为未读，则把状态改成已读,刷新列表和个人信息统计
							$.post('immanage!update.action','imDTO.imId='+rowData.imId+'&imDTO.status=1',function(){
								$('#IMjqGrid').trigger('reloadGrid');
								//showMessager();
							})
						}
						
						if(rowData.sendUsers=='system'){
							document.getElementById('link_im_reply_ok').style.display='none';
						}else{
							document.getElementById('link_im_reply_ok').style.display='';
						}
						if(receive==''){
							receive='receiveUsers='+rowData.sendUsers;
						}else
							receive=receive+"&receiveUsers="+rowData.sendUsers;
						
						if(receiveUsers==''){
							receiveUsers=rowData.sendUsers;
						}else
							receiveUsers=receiveUsers+";"+rowData.sendUsers;
						
						$('#rep_title').val(i18n['label_im_reply']+": "+rowData.title);
					}
					
					$('#rep_toUser').val(receiveUsers+";");
					//打开窗口
					windows('editMessage',{width:500});
				}
			}else{
				msgAlert(i18n['msg_atLeastChooseOneData'],'info');
			}
		},
		check_reply:function(){
			var flag = false;
			$.each($("#IMjqGrid tr td:first-child").children(":checkbox"),function(ind,obj){
				var tr = $(obj).parent().parent();
				var selected = $(tr).attr("aria-selected");
				if(selected=="true"){
					var td = $(tr).find("td[aria-describedby='IMjqGrid_act']");
					var display = $(td).find("#imjqgridact_replay").parent().css("display");
					if(display=="none"){
						flag = true;
						return;
					}
				}
				
			});
			return flag;
		},
		/**
		 * @description回复窗口.
		 */

		im_reply_win:function(){
			$('#rep_content').val('');
			receive='';
			$('#rep_toUser').val('');
			var receiveUsers='';
			var gr='';
			//(imid==''){
				gr = jQuery("#IMjqGrid").jqGrid('getGridParam','selarrrow');
			//}else{
			//	gr = imid;
			//}
					
			if(gr!=null && gr!=''){
				if(gr==null & gr==''){
					msgAlert(i18n['msg_atLeastChooseOneData'],'info');
				}else{
					if(wstuo.infoMge.infoMge.check_reply()){
						msgAlert(i18n['reply_emial_check'],'info');
						return false;
					}
					gr=gr+'';
					var mygr=gr.split(",");
					
					var ids=[];
					for(var i=0;i<mygr.length;i++){
						var rowData=$("#IMjqGrid").getRowData(mygr[i]);
						if(rowData.sendUsers!==userName){
							ids.push(mygr[i]);
						}
						if(rowData.status=='0'){//如果状态为未读，则把状态改成已读,刷新列表和个人信息统计
							$.post('immanage!update.action','imDTO.imId='+rowData.imId+'&imDTO.status=1',function(){
								$('#IMjqGrid').trigger('reloadGrid');
								//showMessager();
							})
						}
						if(rowData.sendUsers=='system'){
							document.getElementById('link_im_reply_ok').style.display='none';
						}else{
							document.getElementById('link_im_reply_ok').style.display='';
						}
						
						if(receive==''){
							receive='receiveUsers='+rowData.sendUsers;
						}else
							receive=receive+"&receiveUsers="+rowData.sendUsers;
						
						if(receiveUsers==''){
							receiveUsers=rowData.sendUsers;
						}else
							receiveUsers=receiveUsers+";"+rowData.sendUsers;
						
						$('#rep_title').val(i18n['label_im_reply']+": "+rowData.title);
					}
					param = $.param({'ids':ids},true);
					$('#rep_toUser').val(receiveUsers+";");
					//打开窗口
					windows('editMessage',{width:500});
				}
				
			}else{
				msgAlert(i18n['msg_atLeastChooseOneData'],'info');
			
			}
			
		},
		/**
		 * @description 接收用户去掉登录用户
		 */
		im_excutionCurrentUser:function(id){
			
			var toUserArr=$(id).val().split(";");
			var toUserStr="";
			
			if(toUserArr!=null && toUserArr.length>0){
				for(var i=0;i<toUserArr.length;i++){
					
					if(toUserArr[i]!=userName && toUserArr[i]!=''){
						
						toUserStr+=toUserArr[i]+';';
					}
				}
			}
			$(id).val(toUserStr);		
			
		},
		
		/**
		 * @description 回复即时消息
		 */
		im_reply:function(){
			wstuo.infoMge.infoMge.im_excutionCurrentUser('#rep_toUser');
				validateUsers($('#rep_toUser').val(),function(replyUser){
					var _param = $('#editMessage form').serialize();
					var _url='immanage!reply.action';	
					var receivesUsers=wstuo.infoMge.infoMge.getReceiveUsers(replyUser);
					
					$.post(_url,_param+"&"+param+"&"+receivesUsers,function(){	
						
						$('#editMessage').dialog('close');
						$('#IMjqGrid').trigger('reloadGrid');

						msgShow(i18n['msg_im_imSendSuccessful'],'show');
						
						//showMessager();//读取IM
						
					});
				});
			
		},

		/**
		 * @description 查看信息.
		 */
		im_look_win:function(grs){
			$('#lookMessage_content').val('');
			var rowData=$("#IMjqGrid").getRowData(grs);	
			$('#look_im_sendUser').text(rowData.sendUsers);
			$('#look_im_sendTime').text(rowData.sendTime);
			$('#look_im_title').text(rowData.title);
			if(immanageReply=="1"){
				if(rowData.sendUsers=='system'){
					var content='<a onclick=look_Details("'+rowData.eventType+'",'+rowData.requestEno+','+rowData.imId+',"lookMessage") >'+rowData.content+'</a>';
					$('#look_im_content').html(content);
					document.getElementById('read_im_reply_send').style.display='none';
					document.getElementById('im_save_detail_1').style.display='none';
					document.getElementById('im_save_detail_2').style.display='none';
					document.getElementById('im_save_detail_3').style.display='none';
				}else{
					document.getElementById('read_im_reply_send').style.display='';
					document.getElementById('im_save_detail_1').style.display='';
					document.getElementById('im_save_detail_2').style.display='';
					document.getElementById('im_save_detail_3').style.display='';
					$('#look_im_content').html(rowData.content);
				}
			}else{
				$('#look_im_content').html(rowData.content);
			}
			if(rowData.sendUsers!=userName){
				$('#lookMessage_toUser').val(rowData.sendUsers);
				if(rowData.status=='0'){//如果状态为未读，则把状态改成已读,刷新列表和个人信息统计
					$.post('immanage!update.action','imDTO.imId='+rowData.imId+'&imDTO.status=1',function(){
						$('#IMjqGrid').trigger('reloadGrid');
						//showMessager();
					})
				}
				$("#im_save_detail").show();
			}else{
				$("#im_save_detail").hide();
			}
			$('#lookMessage_title').val(i18n['label_im_reply']+": "+rowData.title);
			windows('lookMessage',{width:500,modal: true});
		},
		
		/**
		 * @description 回复消息.
		 */
		im_replyMess:function(){
				wstuo.infoMge.infoMge.im_excutionCurrentUser('#lookMessage_toUser');
				var _params = $('#lookMessage form').serialize();
				var _url='immanage!save.action';
				validateUsers($('#lookMessage_toUser').val(),function(replyUser){
					var receivesUsers=wstuo.infoMge.infoMge.getReceiveUsers(replyUser);
					$.post(_url,_params+"&"+receivesUsers,function(){	
						$('#lookMessage').dialog('close');
						$('#IMjqGrid').trigger('reloadGrid');
						
						msgShow(i18n['msg_im_imSendSuccessful'],'show');
						
						//showMessager();//读取IM
						
					});
					
				});				

		},
		/**
		 * @description 删除消息时去掉
		 */
		im_delete:function(){
			checkBeforeDeleteGrid("#IMjqGrid",wstuo.infoMge.infoMge.im_delete_method);
		},
		
		/**
		 * @description 删除
		 * */
		im_delete_method:function(s){
			
				var _param = $.param({'ids':s},true);
			 
				var _url = 'immanage!delete.action';
			
				$.post(_url,_param, function(){
					
					$('#IMjqGrid').trigger('reloadGrid');
					
					msgShow(i18n['msg_im_deleteSuccessful'],'show');
					
					//showMessager();//读取IM
					
				},'json');
		},
		
		/**
		 * @description 行内删除
		 */
		im_delete_inline:function(id){
			msgConfirm(i18n['msg_msg'],'<br/>'+i18n['msg_confirmDelete'],function(){
				wstuo.infoMge.infoMge.im_delete_method(id);
			});
		},

		/**
		 * @description 即时消息内容格式化.
		 */
		contentFormatter:function (cellvalue, options, rowObject){	 		
			//正则表达式
			var reg = new RegExp( '<[^>]+>' , 'g' );
			//字符串中所有的html标签替换成空
			var tstr = cellvalue.replace(reg, '');	   		
			return '<div class="content" style="width:100%;">'+tstr+'</div>';
		},
		senderFullNameFormat:function (cellvalue, options, rowObject){
			if(rowObject.senderFullName==""){
				return rowObject.sendUsers;
			}else{
				return rowObject.senderFullName;
			}
		},
		contentUnFormatter:function(cellvalue,options){
		   return cellvalue;
		},
		/**
		 * @description 国际化状态
		 */
		statusFormat:function(cell,opt,data){
			var status=data.status;
			if(status=='0'){
				status=i18n['label_im_notRead'];
			}else if(status=='1'){
				status=i18n['label_im_readed'];
			}else if(status=='2'){
				status=i18n['label_im_replyed'];
			}
			if(data.sendUsers==userName)
				status=i18n.label_im_send+" [ "+data.receiveUsers+" ]";
			return status;
		},
		contentFormat:function(cellvalue, options){
			return cellvalue.replace(/[\r\n]/g,"");
		},
		senderFullNameFormat:function (cellvalue, options, rowObject){
			if(rowObject.senderFullName==null || rowObject.senderFullName==""){
				return rowObject.sendUsers;
			}else{
				return rowObject.senderFullName;
			}
		},
		/**
		 * @description IM列表操作项格式化.
		 */
		
		IMGridFormatter:function(cell,opt,data){
			var html=$('#imgridact').html().replace(/\{imid}/g,data.imId);
			if(data.sendUsers!=userName && data.sendUsers!='system')
				html=html.replace(/none/g,'');
			
			return html;
		},
		
		/**
		 * @description 加载数据列表.
		 */
		showIMGrid:function(){
			
			var params = $.extend({},jqGridParams, {	
				url:'immanage!findPager.action?manageQueryDTO.receiveUsers='+userName+'&manageQueryDTO.sendUsers='+userName,
				colNames:[i18n['common_title'],i18n['title_sendUser'],i18n['common_content'],i18n['common_state'],i18n['title_sendTime'],i18n['common_action'],'','','','','',''],
				colModel:[
						  {name:'title',width:80,align:'left'},
						  {name:'senderFullName',width:80,index:'sendUsers',align:'center',formatter:wstuo.infoMge.infoMge.senderFullNameFormat},
						  {name:'content',width:100,align:'left',sortable:false,formatter:wstuo.infoMge.infoMge.contentFormat},
						  {name:'status',width:80,align:'left',formatter:wstuo.infoMge.infoMge.statusFormat},
						  {name:'sendTime',width:80,align:'center',formatter:timeFormatter},
						  {name:'act',width:80,align:'center',sortable:false,formatter:wstuo.infoMge.infoMge.IMGridFormatter},
						  {name:'imId',hidden:true},
						  {name:'status',hidden:true},
						  {name:'sendUsers',hidden:true},
						  {name:'receiveUsers',hidden:true},
						  {name:'eventType',hidden:true},
						  {name:'requestEno',hidden:true}
						  ],
				toolbar: [true,"top"],
				jsonReader: $.extend(jqGridJsonReader, {id:"imId"}),
				sortname:'imId',
				sortorder:'desc',
				ondblClickRow:function(rowId){wstuo.infoMge.infoMge.im_look_win(rowId)},
				pager:'#IMpager'
			});
			$("#IMjqGrid").jqGrid(params);
			$("#IMjqGrid").navGrid('#IMpager',navGridParams);
			//列表操作项
			$("#t_IMjqGrid").css(jqGridTopStyles);
			$("#t_IMjqGrid").append($('#IMgridToolbar').html());
			//自适应宽度
			//setGridWidth("#IMjqGrid","regCenter",20);
			
		},
		
	  /**
	   * @description 选择用户.
	   */
	  selectImUser:function(userNamesPut,_companyNo){
		  wstuo.user.userUtil.selectUserMulti(userNamesPut,'','loginName',_companyNo);
	  },
	  /**
	   * @description 初始化
	   */
	  init: function(){
		//绑定日期控件
		  DatePicker97(['#manageQueryDTO_sendSatrt','#manageQueryDTO_sendEnd']);
		//加载数据列表
		    wstuo.infoMge.infoMge.showIMGrid();
			//动态创建事件

			$('#link_im_reply_ok').click(wstuo.infoMge.infoMge.im_reply);
			$("#link_im_search_ok").click(wstuo.infoMge.infoMge.search_do);	
	
			$("#read_im_reply_send").click(wstuo.infoMge.infoMge.im_replyMess);	
			
			
			$('#write_im_sendUser').click(function(){
				wstuo.infoMge.infoMge.selectImUser('#receiveUsers',companyNo);
			});
			
			$('#write_im_reply').click(function(){
				
				wstuo.infoMge.infoMge.selectImUser('#rep_toUser',companyNo);
			});
			
			$('#write_im_reply2').click(function(){
				
				wstuo.infoMge.infoMge.selectImUser('#lookMessage_toUser',companyNo);
			});
			
			
			$('#im_search_sendUsers').unbind().click(function(){
				wstuo.user.userUtil.selectUser('#manageQueryDTO_sendUsers','','','fullName',companyNo);
			});
			
	  }
	  
	};
}();
//载入
$(document).ready(wstuo.infoMge.infoMge.init);

